﻿//#define GENERATE_DEFAULT_SETTINGS
using System;
using System.Net;
using System.Xml.Serialization;
using ScheduleMVVM.Model.Miscellaneous;

namespace ScheduleMVVM.Model.PersistentFramework
{
    public sealed partial class Settings
    {
        /// <summary>
        /// Service field
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        public SyncableXml<Settings> settingsXML;
        /// <summary>
        /// Service field
        /// </summary>
        public static Settings _self;
        /// <summary>
        /// Current application settings. Reverted to defaults if settings.xml is not present. Settings are blank if WINDOWS_PHONE flag is inactive.
        /// </summary>
        public static Settings Current
        {
            get
            {
                if (_self == null) _self = Create();
                return _self;
            }
        }
        private static Settings Create()
        {
#if WINDOWS_PHONE
            var settingsDescriptor = new SyncableXml<Settings>("settings.xml");
#if GENERATE_DEFAULT_SETTINGS
            settingsDescriptor.Value = new Settings()
            {
                RelevanceTimeout = 25,
                MaximumDisplayedResults = 10,
                CurrentEngineIndex = 0,
                Engines = new BaseEngine[1] 
                {
                    (BaseEngine)(new TUTUruEngine() )
                }
            };
#endif
            if (!settingsDescriptor.DataPresent)
                //settingsDescriptor.CopyFromStream(App.GetResourceStream(new Uri(@"Prerequisites/DefaultSettings.xml", UriKind.Relative)).Stream);
                throw new InvalidOperationException();
            settingsDescriptor.Value.settingsXML = settingsDescriptor;
            return settingsDescriptor.Value;
#else 
            return new Settings();
#endif
        }
        /// <summary>
        /// Synchronizes application settings with XML storage
        /// </summary>
        public void Synchronize()
        {
            settingsXML.Sync();
        }
        [System.Xml.Serialization.XmlIgnore]
        private BaseEngine _currentEngine;
        /// <summary>
        /// Active application search engine
        /// </summary>
        [System.Xml.Serialization.XmlIgnore]
        public BaseEngine CurrentEngine
        {
            get
            {
                if (_currentEngine == null)
                {
#if WINDOWS_PHONE
                    var currentEngine = Engines[CurrentEngineIndex];
                    if (currentEngine.ClassName == "TUTUruEngine") _currentEngine = new TUTUruEngine();
#else
                    _currentEngine = new TUTUruEngine();
#endif
                }
                return _currentEngine;
            }
        }
    }
}
